package org.bigk.invoices.services;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bigk.invoices.exceptions.ServiceException;
import org.bigk.invoices.model.Invoice;
import org.bigk.invoices.model.PaymentKind;

public class InvoicesServiceImplDzieciolandia extends InvoicesServiceImpl {
	/**
	 * Logger for this class
	 */
	private static final Log logger =
		LogFactory.getLog(InvoicesServiceImplDzieciolandia.class);

	public Invoice prepareNewInvoice() throws ServiceException {
		if (logger.isDebugEnabled()) {
			logger.debug("prepareNewInvoice() - start");
		}
		
		Invoice invoice = null;
		if (this.invoiceTemplate != null) {
			try {
				invoice = invoiceTemplate.clone();
			} catch (CloneNotSupportedException e) {
				logger.warn("prepareNewInvoice()", e);
			}
		}
		
		if (invoice == null) {
			invoice = new Invoice();
		}

		Calendar nowDay = Calendar.getInstance();
		nowDay.set(Calendar.HOUR, 0);
		nowDay.set(Calendar.MINUTE, 0);
		nowDay.set(Calendar.SECOND, 0);
		nowDay.set(Calendar.MILLISECOND, 0);
		
		String curYear = Integer.toString(nowDay.get(Calendar.YEAR));
		String curMonth = Integer.toString(nowDay.get(Calendar.MONTH) + 1);
		curMonth = StringUtils.right("0" + curMonth, 2);
		
		curYear += "/" + curMonth;
		invoice.setYear(curYear);
		
		int maxInvoiceNumber = this.getMaxInvoiceNumber(curYear);
		maxInvoiceNumber++;
		
		Long number = new Long(maxInvoiceNumber);
		invoice.setNumber(number);
		invoice.setDocumentDate(nowDay.getTime());
		invoice.setSoldDate(nowDay.getTime());
		
		PaymentKind pk = null;
		if (invoice.getPaymentKindId() != null) {
			pk = paymentKindsService.getPaymentKind(invoice.getPaymentKindId());
		}
		
		Date paymentDate = null;
		if (pk != null) {
			invoice.setPaymentKind(pk);
			paymentDate = paymentKindsService.calculatePaymentDate(nowDay.getTime(), pk.getId());
			invoice.setPaymentDate(paymentDate);
		}
		
		recalculateInvoice(invoice);
		hrInvoiceNumberService.updateHRInvoiceNumber(invoice);

		if (logger.isDebugEnabled()) {
			logger.debug("prepareNewInvoice() - end - return value=" + invoice);
		}
		return invoice;
	}
}
